package com.zhang.hadoop.netty.nio.channel;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author: zhang yufei
 * @create: 2022-01-09 16:38
 * @description: 同一个buffer读写数据
 **/
public class NIOFileChannel03 {

    public static void main(String[] args) {
        try {
            //文件放到项目下则可以直接使用
            FileInputStream fileInputStream = new FileInputStream("1.txt");
            FileChannel fileChannel01 = fileInputStream.getChannel();

            FileOutputStream fileOutputStream = new FileOutputStream("2.txt");
            FileChannel fileChannel02 = fileOutputStream.getChannel();

            ByteBuffer byteBuffer = ByteBuffer.allocate(512);

            while (true) {
                //清空buffer，如果buffer小于文件大小，则必须清空，复位数据使用
                byteBuffer.clear();
                int read = fileChannel01.read(byteBuffer);
                if (read == -1) {
                    break;
                }
                //将buffer中的数据写入到fileChannel02
                byteBuffer.flip();
                fileChannel02.write(byteBuffer);
            }

            //关闭相关流
            fileInputStream.close();
            fileOutputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
